import { Modal, Button, Form, Input } from 'antd'
import React, { useState } from 'react'
import { register } from '@/api/users'

export default (props: any) => {
  const [isModalVisible, setModalVisible] = useState(false)

  const [form] = Form.useForm()  // 表单数据域进行交互

  // 显示对话框
  const showModal = () => {
    // 每次打开modal 时 重置表单字段的值
    form.setFieldsValue({
      username: null,
      password: null,
      confirm: null
    })
    setModalVisible(true)
  }

  // 确认
  const handleOk = async () => {
    const fieldValue = await form.validateFields()
    // console.log(filedValue);
    const params = {
      username: fieldValue.username,
      password: fieldValue.password
    }

    // 网络请求 添加用户
    register(params).then((res: any) => {
      console.log(res);
      props.handleInsert()
    })

    setModalVisible(false)
  }

  // 取消
  const handleCancel = () => {
    setModalVisible(false)
  }

  // 表单提交时触发的回调 收集到的是你表单的字段
  const onFinish = (values: any) => {

  }


  return (
    <>
      <Button type='primary' onClick={showModal} style={{ margin: '10px 0 10px 10px' }} >添加</Button>

      <Modal title="添加用户"
        visible={isModalVisible}
        // onOk={handleOk}
        onCancel={handleCancel}
        footer={[
          <Button key='1' type='primary' htmlType='submit' onClick={handleOk}>确认</Button>,
          <Button key='2' type='primary' onClick={handleCancel}>取消</Button>
        ]}
      >
        <Form
          labelCol={{ span: 4, offset: 3 }}
          onFinish={onFinish}
          form={form}
          initialValues={{
            user: '',
            password: ''
          }}
        >
          <Form.Item label='用户名' rules={[{ required: true, message: '请输入用户名！' }]} name='username'>
            <Input placeholder='请输入用户名' />
          </Form.Item>

          <Form.Item label='密码' name='password' rules={[{ required: true, message: '请输入密码！' }]}>
            <Input.Password placeholder='请输入密码' type='password' name='password' />
          </Form.Item>

          {/* 使用dependencies 属性进行依赖 就是作为密码确认验证 */}
          <Form.Item
            label='确认密码'
            name='confirm'
            dependencies={['password']}
            rules={[
              {
                required: true,
                message: 'Please confirm your password!',
              },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('请确认你的密码'));
                },
              }),
            ]}
          >
            <Input.Password placeholder='确认密码' type='password' />
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}